package com.centaline.androidsalesblog.activities.newest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.LoanCalcActivity;
import com.centaline.androidsalesblog.adapter.ImgListBrowseAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.NewPropImgBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropImgQueryBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.service.ImageDownloadService;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 新盘户型图
 * Created by guilin on 16/2/25.
 */
public class NewEstHouseTypeActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager viewPager;
    private AppCompatTextView atv_title, atv_desc, atv_price;
    private LinearLayout ll_calculator;


    private ImgListBrowseAdapter imgListBrowseAdapter;
    private ArrayList<String> imgList = new ArrayList<>();//显示图片合集
    private ArrayList<String> imgListThumbnail = new ArrayList<>();//缩略图片合集
    private ArrayList<NewPropImgBo> newPropImgBos = new ArrayList<>();//新房图片合集
    private double avgPrice;//均价
    private double totalPrice;//总价
    protected int currentPos;//当前位置
    private String newPropImg;

    private ImageDownloadService.DownloadBinder downloadBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (ImageDownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_house_type;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        atv_title = (AppCompatTextView) findViewById(R.id.atv_title);
        atv_desc = (AppCompatTextView) findViewById(R.id.atv_desc);
        ll_calculator = (LinearLayout) findViewById(R.id.ll_calculator);
        atv_price = (AppCompatTextView) findViewById(R.id.atv_price);
    }

    @Override
    protected void initViews() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        imgListBrowseAdapter = new ImgListBrowseAdapter(viewPager, GlideLoad.init(this), imgList, imgListThumbnail);
        viewPager.setAdapter(imgListBrowseAdapter);

        currentPos = getIntent().getIntExtra(ExtraConstant.IMG_POS, 0);
        avgPrice = getIntent().getDoubleExtra(ExtraConstant.Price, 0);
        ArrayList<NewPropImgBo> temp = getIntent().getParcelableArrayListExtra(ExtraConstant.NewPropImgList);
        newPropImgBos.addAll(temp);
        bindService(new Intent(this, ImageDownloadService.class), serviceConnection, BIND_AUTO_CREATE);
        bizUnit();
    }

    private void initData() {
        for (NewPropImgBo newPropImgBo : newPropImgBos) {
            String imgAddress = newPropImgBo.getFileUrl();
            String imgAddressThumb = newPropImgBo.getFileUrl();
            imgAddress = imgAddress == null || !imgAddress.contains(".") ? "" :
                    String.format(Locale.CHINA,
                            "%s%s",
                            newPropImg,
                            imgAddress.replace(".",
                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth(), newPropImgBo.getHeight())));
            imgAddressThumb = imgAddressThumb == null || !imgAddressThumb.contains(".") ? "" :
                    String.format(Locale.CHINA,
                            "%s%s",
                            newPropImg,
                            imgAddressThumb.replace(".",
                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth() * 10 / 100, newPropImgBo.getHeight() * 10 / 100)));
            imgListThumbnail.add(imgAddressThumb);
            imgList.add(imgAddress);
        }
        imgListBrowseAdapter.notifyDataSetChanged();
        if (currentPos > 0) {
            viewPager.setCurrentItem(currentPos);
        }
        pageSelected(currentPos);
    }

    protected void pageSelected(int position) {
        currentPos = position;
        setToolbarTitle(String.format(Locale.CHINA, "%d/%d", position + 1, imgList.size()));
        final NewPropImgBo newPropImgBo = newPropImgBos.get(position);
        final NewPropImgQueryBo newPropImgQueryBo = newPropImgBo.getNewPropImgQueryBo();
        if (newPropImgQueryBo != null) {
            atv_title.setText(newPropImgQueryBo.getHouseTypeName());
            atv_desc.setText(String.format(Locale.CHINA, "%d室%d厅 %d平",
                    newPropImgQueryBo.getRoomCnt(), newPropImgQueryBo.getHallCnt(), newPropImgQueryBo.getArea()));
            if (avgPrice == 0 ||
                    newPropImgQueryBo.getArea() == 0) {
                totalPrice = 0;
                atv_price.setText("0万");
            } else {
                String price = String.format(Locale.CHINA, "%.0f", avgPrice * newPropImgQueryBo.getArea() / 10000);
                totalPrice = Double.parseDouble(price) * 10000;
                atv_price.setText(String.format(Locale.CHINA, "%s万", price));
            }
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_calculator:
                Bundle bundle = new Bundle();
                bundle.putDouble(ExtraConstant.LOAN_PRICE, totalPrice);
                startActivity(new Intent(this, LoanCalcActivity.class)
                        .putExtra(ExtraConstant.LOAN_BUNDLE, bundle));
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (imgList.size() > 0)
            getMenuInflater().inflate(R.menu.menu_download, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_download) {
            downloadBinder.startDownload(imgList.get(currentPos));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取配置信息
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        newPropImg = bizUnitDo.getNewpropimg();
                        initData();
                    }
                });
    }
}
